package com.ayz.gateway.client.connection;


import com.ayz.gateway.client.ServerInfo;
import com.ayz.gateway.client.exception.ExecuteRequestException;
import com.ayz.gateway.client.executor.RequestExecutor;
import com.ayz.gateway.client.executor.RequestExecutorRegistry;
import com.ayz.gateway.client.executor.ResponseCallback;
import lombok.Data;

import java.util.concurrent.TimeoutException;

/**
 * @ClassName AbstractConnection
 * @Description TODO: 抽象的连接
 * @Author 快乐的星球
 * @Date 2023/5/20 15:37
 * @Version 1.0
 **/
@Data
public abstract class AbstractConnection implements Connection{
    /**
     * 服务端的详细信息
     */
    private ServerInfo serverInfo;
    /**
     * 请求执行器注册器
     */
    private RequestExecutorRegistry requestExecutorRegistry;
    /**
     * 连接的唯一标识
     * 格式 "timestamp_serverIp_serverPort"
     */
    private String connectionId;
    public AbstractConnection(ServerInfo serverInfo, RequestExecutorRegistry requestExecutorRegistry){
        this.serverInfo=serverInfo;
        this.requestExecutorRegistry=requestExecutorRegistry;
    }

    @Override
    public void start() {
        StringBuilder sb=new StringBuilder();
        //1: 连接的唯一标识符
        this.connectionId = sb.append(System.currentTimeMillis()).append("_").append(getServerInfo().getIp())
                .append("_").append(getServerInfo().getPort()).toString();
    }

    @Override
    public Object request(int requestCode, Object request, long timeoutMills) throws TimeoutException {
        RequestExecutor requestExecutor = getRequestExecutorRegistry().getRequestExecutor(requestCode);
        return requestExecutor.request(request, timeoutMills);
    }

    @Override
    public void asyncRequest(int requestCode, Object request, ResponseCallback responseCallback) throws TimeoutException, ExecuteRequestException {
        RequestExecutor requestExecutor = getRequestExecutorRegistry().getRequestExecutor(requestCode);
        requestExecutor.asyncRequest(request,responseCallback);
    }

    @Override
    public void requestOneway(int requestCode, Object request) throws ExecuteRequestException {
        RequestExecutor requestExecutor = getRequestExecutorRegistry().getRequestExecutor(requestCode);
        requestExecutor.requestOneway(request);
    }
}
